package com.xiemulei.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiemulei.common.utils.PageUtils;
import com.xiemulei.common.utils.Query;
import com.xiemulei.gulimall.product.dao.CategoryDao;
import com.xiemulei.gulimall.product.entity.CategoryEntity;
import com.xiemulei.gulimall.product.service.CategoryBrandRelationService;
import com.xiemulei.gulimall.product.service.CategoryService;
import com.xiemulei.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类


        return entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).peek((menu) -> menu.setChildren(getChildren(menu, entities))).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     */

//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'level1Categories'"),
//            @CacheEvict(value = "category", key = "'catalogJSON'"),
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = "category", key = "'level1Categories'")
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("getLevel1Categories......");
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category", key = "'catalogJSON'")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
//        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
//        if (StringUtils.hasLength(catalogJSON)) {
//            System.out.println("缓存命中，直接返回");
//            TypeReference<Map<String, List<Catelog2Vo>>> typeReference = new TypeReference<>() {
//            };
//            return JSON.parseObject(catalogJSON, typeReference);
//        } else {
//            System.out.println("缓存未命中，查询数据库");

        return getCatalogJsonFromDbWithRedissonLock();
//        }
    }

    // 从数据查询并获取数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        // 占分布式锁
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();

        // 加锁成功，执行业务
        Map<String, List<Catelog2Vo>> data;
        try {
            data = getDataFromDb();
        } finally {
            lock.unlock();
        }

        return data;

    }


    private Map<String, List<Catelog2Vo>> getDataFromDb() {
//        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
//        if (StringUtils.hasLength(catalogJSON)) {
//            TypeReference<Map<String, List<Catelog2Vo>>> typeReference = new TypeReference<>() {
//            };
//            return JSON.parseObject(catalogJSON, typeReference);
//        }
//
//        System.out.println("查询数据库");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 查出所有1级分类
        List<CategoryEntity> level1Categories = getSelectedCategories(categoryEntities, 0L);
        Map<String, List<Catelog2Vo>> collect = level1Categories.stream().collect(
                Collectors.toMap(k -> k.getCatId().toString(), l1 -> {
                            // 查到1级分类下的2级分类
                            List<CategoryEntity> level2Categories = getSelectedCategories(categoryEntities, l1.getCatId());
                            // 封装上面的结果
                            List<Catelog2Vo> catelog2Vos = null;
                            if (level2Categories != null) {
                                catelog2Vos = level2Categories.stream().map(l2 -> {
                                    Catelog2Vo catelog2Vo = new Catelog2Vo(
                                            l1.getCatId().toString(),
                                            null,
                                            l2.getCatId().toString(),
                                            l2.getName()
                                    );
                                    // 找到当前2级分类下的三级分类，并进行封装
                                    List<CategoryEntity> level3Categories = getSelectedCategories(categoryEntities, l2.getCatId());
                                    if (level3Categories != null) {
                                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Categories
                                                .stream()
                                                .map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())).collect(Collectors.toList());
                                        catelog2Vo.setCatalog3List(catelog3Vos);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                            }
                            return catelog2Vos;
                        }
                ));
//        String s = JSON.toJSONString(collect);
//        stringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return collect;

    }


    /**
     * 查询出父ID为 parent_cid 的 CategoryEntity 集合
     */
    private List<CategoryEntity> getSelectedCategories(List<CategoryEntity> categoryEntities, Long parentCid) {
        return categoryEntities.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;

    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        return all.stream().filter(categoryEntity -> Objects.equals(categoryEntity.getParentCid(), root.getCatId())).peek(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    }


}